from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
import os

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_name='default'):
    from config import config
    
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    CORS(app)
    
    # 注册蓝图 - 先检查路由文件是否存在
    try:
        from app.routes.datasource import datasource_bp
        app.register_blueprint(datasource_bp, url_prefix='/api/datasource')
    except ImportError:
        pass
    
    try:
        from app.routes.sync_task import sync_task_bp
        app.register_blueprint(sync_task_bp, url_prefix='/api/sync_task')
    except ImportError:
        pass
    
    try:
        from app.routes.sync_log import sync_log_bp
        app.register_blueprint(sync_log_bp, url_prefix='/api/sync_log')
    except ImportError:
        pass
    
    try:
        from app.routes.sync_stats import sync_stats_bp
        app.register_blueprint(sync_stats_bp, url_prefix='/api/sync_stats')
    except ImportError:
        pass
    
    try:
        from app.routes.fake_data import fake_data_bp
        app.register_blueprint(fake_data_bp, url_prefix='/api/fake-data')
    except ImportError:
        pass
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app